import { ref, onMounted, onUnmounted, watch, type Ref } from 'vue';
import type { ExamInfo } from '#/api/manage/type';
import { useMessageBox } from '#/hooks/useMessageBox';
import { $t } from '#/locales';
import { useFetchCopyCount, saveCopyCount, useFetchCutCount, saveCutCount } from './useApi';

const { confirm: confirmBox } = useMessageBox();

// 安全校验相关类型
interface SecurityViolation {
  switchCount: number;
  copyCount: number;
}

export function useExamSecurity(
  handleConfirmSubmit: (reason?: string, submit?: boolean) => void,
  examInfo: Ref<ExamInfo | undefined>,
  examScoreId: string
) {
  const copyCount = useFetchCopyCount(examScoreId);
  const cutCount = useFetchCutCount(examScoreId);
  const securityViolation = ref<SecurityViolation>({
    switchCount: 0,
    copyCount: 0
  });

  watch(() => copyCount.value, (newCopyCount) => {
    securityViolation.value.copyCount = newCopyCount;
  });

  watch(() => cutCount.value, (newCutCount) => {
    securityViolation.value.switchCount = newCutCount;
  });

  const isExamTerminated = ref(false);

  // 窗口状态监控
  const windowState = ref({
    isMaximized: true,
    isAppFocused: true,
    isProcessingSwitch: false
  });

  // 定时器管理
  const timers = ref({
    windowCheckTimer: null as ReturnType<typeof setTimeout> | null,
    appFocusTimer: null as ReturnType<typeof setTimeout> | null,
    switchProcessingTimer: null as ReturnType<typeof setTimeout> | null
  });

  // 切换事件去重函数
  const isDuplicateSwitchEvent = (eventType: 'visibilitychange' | 'blur' | 'pagevisibility'): boolean => {
    if (windowState.value.isProcessingSwitch) {
      console.log(`${eventType} event ignored - switch processing in progress`);
      return true;
    }

    windowState.value.isProcessingSwitch = true;
    console.log(`${eventType} event accepted - starting switch processing`);

    if (timers.value.switchProcessingTimer) {
      clearTimeout(timers.value.switchProcessingTimer);
    }
    
    timers.value.switchProcessingTimer = setTimeout(() => {
      windowState.value.isProcessingSwitch = false;
      console.log('Switch processing completed, ready for next event');
    }, 200);

    return false;
  };

  // 检查切屏和应用切换总违规次数
  const checkTotalSwitchViolations = () => {
    const totalSwitchCount = securityViolation.value.switchCount;
    const maxCount = examInfo.value?.configuration?.suppressSwitchingScreenCount || 0;
    
    saveCutCount(examScoreId);
    
    if (totalSwitchCount >= maxCount && maxCount > 0) {
      handleSecurityViolation($t('examCore.securityViolation.totalSwitchExceeded', {
        totalCount: totalSwitchCount,
        maxCount: maxCount
      }));
    }
  };

  // 切屏检测
  const handleVisibilityChange = () => {
    if (document.hidden && !isExamTerminated.value && examInfo.value?.configuration?.suppressSwitchingScreen) {
      if (isDuplicateSwitchEvent('visibilitychange')) {
        return;
      }
      
      securityViolation.value.switchCount++;
      console.log('Switch screen detected via visibilitychange, switchCount:', securityViolation.value.switchCount);
      
      confirmBox($t('examCore.securityViolation.switchScreenWarning', {
        count: securityViolation.value.switchCount,
        maxCount: examInfo.value?.configuration?.suppressSwitchingScreenCount
      }), {
        showCancelButton: false,
        showConfirmButton: false
      });
      
      checkTotalSwitchViolations();
    }
  };

  // 检测窗口是否最大化
  const checkWindowMaximized = (): boolean => {
    const availWidth = screen.availWidth;
    const availHeight = screen.availHeight;
    const windowWidth = window.outerWidth;
    const windowHeight = window.outerHeight;
    const tolerance = 10;

    const isMaximizedWidth = Math.abs(windowWidth - availWidth) <= tolerance;
    const isMaximizedHeight = Math.abs(windowHeight - availHeight) <= tolerance;

    return isMaximizedWidth && isMaximizedHeight;
  };

  // 显示初始化时的窗口最大化要求弹窗
  const showInitialMaximizeDialog = () => {
    confirmBox($t('examCore.securityViolation.windowNotMaximizedInitial'), {
      showCancelButton: false,
      showConfirmButton: true,
      beforeClose: (action: string, instance: any, done: () => void) => {
        const isMaximizedNow = checkWindowMaximized();
        if (!isMaximizedNow && !isExamTerminated.value) {
          console.warn('窗口未最大化，不允许关闭弹窗');
          return;
        } else {
          windowState.value.isMaximized = true;
          done();
        }
      }
    }).then(() => {
      windowState.value.isMaximized = true;
    }).catch(() => {
      console.log('弹窗被取消或出现错误');
    });
  };

  // 窗口大小变化处理
  const handleWindowResize = () => {
    if (timers.value.windowCheckTimer) {
      clearTimeout(timers.value.windowCheckTimer);
    }
    
    timers.value.windowCheckTimer = setTimeout(() => {
      const isCurrentlyMaximized = checkWindowMaximized();
      if (!isCurrentlyMaximized && !isExamTerminated.value) {
        windowState.value.isMaximized = false;
        showInitialMaximizeDialog();
      } else {
        windowState.value.isMaximized = true;
      }
      timers.value.windowCheckTimer = null;
    }, 300);
  };

  // 应用失去焦点检测 - 只用于检测应用切换，不用于tab页切换
  const handleWindowBlur = () => {
    if (!isExamTerminated.value) {
      windowState.value.isAppFocused = false;

      // 检查是否是tab页切换导致的blur
      if (document.hidden) {
        // 如果是tab页切换，不在这里处理，让visibilitychange处理
        return;
      }

      if (isDuplicateSwitchEvent('blur')) {
        console.log('Duplicate blur detection ignored');
        return;
      }
      
      securityViolation.value.switchCount++;
      console.log('App switch detected via blur, switchCount:', securityViolation.value.switchCount);

      checkTotalSwitchViolations();

      if (timers.value.appFocusTimer) {
        clearTimeout(timers.value.appFocusTimer);
      }
      
      timers.value.appFocusTimer = setTimeout(() => {
        if (!windowState.value.isAppFocused && !isExamTerminated.value) {
          console.log('Showing blur warning dialog');
          confirmBox($t('examCore.securityViolation.switchScreenWarning', {
            count: securityViolation.value.switchCount,
            maxCount: examInfo.value?.configuration?.suppressSwitchingScreenCount
          }), {
            showCancelButton: false,
            showConfirmButton: true,
          });
        }
        timers.value.appFocusTimer = null;
      }, 100);
    }
  };

  // 应用获得焦点
  const handleWindowFocus = () => {
    windowState.value.isAppFocused = true;
    if (timers.value.appFocusTimer) {
      clearTimeout(timers.value.appFocusTimer);
      timers.value.appFocusTimer = null;
    }
  };

  // 页面可见性变化检测
  const handlePageVisibilityChange = () => {
    if (document.hidden && !isExamTerminated.value) {
      if (isDuplicateSwitchEvent('pagevisibility')) {
        console.log('Duplicate page visibility detection ignored');
        return;
      }

      securityViolation.value.switchCount++;
      console.log('Page hidden detected via visibilitychange, switchCount:', securityViolation.value.switchCount);

      checkTotalSwitchViolations();

      if (examInfo.value?.configuration?.suppressSwitchingScreen) {
        console.log('Showing page hidden warning dialog');
        confirmBox($t('examCore.securityViolation.pageHiddenWarning', {
          count: securityViolation.value.switchCount,
          maxCount: examInfo.value?.configuration?.suppressSwitchingScreenCount
        }), {
          showCancelButton: false,
          showConfirmButton: true,
        });
      } else {
        console.log('Page switching detected but suppressSwitchingScreen is disabled');
      }
    }
  };

  // 统一的复制粘贴事件处理
  const handleCopyPasteEvent = (event: Event) => {
    if (!isExamTerminated.value && examInfo.value?.configuration?.suppressCopyAndPaste) {
      // 右键仅阻止默认，不计数、不弹窗
      if (event.type === 'contextmenu') {
        event.preventDefault();
        return;
      }

      // 复制/粘贴以及快捷键触发：阻止并计数、提示
      event.preventDefault();
      securityViolation.value.copyCount++;
      saveCopyCount(examScoreId);
      
      confirmBox($t('examCore.securityViolation.copyWarning', {
        count: securityViolation.value.copyCount,
        maxCount: examInfo.value?.configuration.suppressCopyAndPasteCount
      }), {
        showCancelButton: false,
        showConfirmButton: false
      });
      
      if (securityViolation.value.copyCount >= examInfo.value?.configuration.suppressCopyAndPasteCount) {
        handleSecurityViolation($t('examCore.securityViolation.copyExceeded'));
      }
    }
  };

  // 键盘事件处理 - 只处理Ctrl+C和Ctrl+V
  const handleKeyDown = (event: KeyboardEvent) => {
    if (!isExamTerminated.value && examInfo.value?.configuration?.suppressCopyAndPaste) {
      // 只处理Ctrl+C和Ctrl+V
      if (event.ctrlKey && (event.key === 'c' || event.key === 'v')) {
        handleCopyPasteEvent(event);
      }

      // 禁用F12开发者工具
      if (event.key === 'F12') {
        event.preventDefault();
      }
    }
  };

  // 安全违规处理
  const handleSecurityViolation = async (reason: string) => {
    isExamTerminated.value = true;
    clearAllTimers();
    try {
      await handleConfirmSubmit(reason, true);
    } catch (error) {
      console.error($t('examCore.securityViolation.violationHandleError'), error);
    }
  };

  // 清理所有定时器
  const clearAllTimers = () => {
    Object.keys(timers.value).forEach(key => {
      const timerKey = key as keyof typeof timers.value;
      if (timers.value[timerKey]) {
        clearTimeout(timers.value[timerKey]!);
        timers.value[timerKey] = null;
      }
    });
  };

  // 启动安全监控
  const startSecurityMonitoring = () => {
    console.log('Starting security monitoring...');
    
    // 窗口最大化检测
    const initialMaximized = checkWindowMaximized();
    windowState.value.isMaximized = initialMaximized;
    if (!initialMaximized) {
      showInitialMaximizeDialog();
    }
    window.addEventListener('resize', handleWindowResize);
    
    // 应用切换检测
    if (examInfo.value?.configuration?.suppressSwitchingScreen) {
      console.log('Enabling comprehensive screen switching monitoring...');
      document.addEventListener('visibilitychange', handleVisibilityChange);
      window.addEventListener('blur', handleWindowBlur);
      window.addEventListener('focus', handleWindowFocus);
    } else {
      console.log('Enabling basic page visibility monitoring...');
      // document.addEventListener('visibilitychange', handlePageVisibilityChange);
    }
    
    // 复制粘贴限制
    if (examInfo.value?.configuration?.suppressCopyAndPaste) {
      // 禁用右键菜单
      document.addEventListener('contextmenu', handleCopyPasteEvent);
      // 禁用复制事件
      document.addEventListener('copy', handleCopyPasteEvent);
      // 禁用粘贴事件
      document.addEventListener('paste', handleCopyPasteEvent);
      // 禁用键盘快捷键
      document.addEventListener('keydown', handleKeyDown);
    }
    
    console.log('Security monitoring started');
  };

  // 停止安全监控
  const stopSecurityMonitoring = () => {
    console.log('Stopping security monitoring...');

    window.removeEventListener('resize', handleWindowResize);
    window.removeEventListener('blur', handleWindowBlur);
    window.removeEventListener('focus', handleWindowFocus);
    document.removeEventListener('visibilitychange', handlePageVisibilityChange);
    document.removeEventListener('visibilitychange', handleVisibilityChange);
    document.removeEventListener('contextmenu', handleCopyPasteEvent);
    document.removeEventListener('copy', handleCopyPasteEvent);
    document.removeEventListener('paste', handleCopyPasteEvent);
    document.removeEventListener('keydown', handleKeyDown);

    clearAllTimers();
    console.log('Security monitoring stopped');
  };

  // 生命周期管理
  onMounted(() => {
    if (examInfo.value) {
      startSecurityMonitoring();
    }
  });

  watch(examInfo, (newExamInfo) => {
    if (newExamInfo) {
      stopSecurityMonitoring();
      startSecurityMonitoring();
    }
  }, { immediate: true });

  onUnmounted(() => {
    stopSecurityMonitoring();
  });

  return {
    securityViolation: securityViolation.value,
    windowState: windowState.value,
    isExamTerminated,
    startSecurityMonitoring,
    stopSecurityMonitoring,
    clearAllTimers,
    checkWindowMaximized
  };
}
